#include "HelloPlayerQt.h"
#include "AVPlayerProxy.h"
#include <QMimeData>

HelloPlayerQt::HelloPlayerQt(QWidget *parent) : QMainWindow(parent) {
    ui.setupUi(this);

    ui.imgWidget->setAttribute(Qt::WA_OpaquePaintEvent);
    ui.imgWidget->setAttribute(Qt::WA_NoSystemBackground);
    ui.imgWidget->setFocusPolicy(Qt::StrongFocus);
    ui.imgWidget->setAttribute(Qt::WA_PaintOnScreen);
    AVPlayerProxy::Init(reinterpret_cast<void *>(ui.imgWidget->winId()),
                        ui.imgWidget->width(), ui.imgWidget->height());

    UpdateState();
}

HelloPlayerQt::~HelloPlayerQt() {}

void HelloPlayerQt::on_startButton_clicked() {
    switch (state) {
    case HelloPlayerQt::State::BEGIN:
        state = HelloPlayerQt::State::PLAYING;
        break;
    case HelloPlayerQt::PLAYING:
        state = HelloPlayerQt::State::PAUSED;
        break;
    case HelloPlayerQt::PAUSED:
        state = HelloPlayerQt::State::PLAYING;
        break;
    default:
        break;
    }
    UpdateState();
    Play("C:\\Users\\zhou\\Desktop\\龙猫.BD1280高清中字版.mp4");
}

void HelloPlayerQt::dragEnterEvent(QDragEnterEvent *event) {
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction(); // 3. 有拖拽文件时设置接受
    }
}

void HelloPlayerQt::dropEvent(QDropEvent *event) {
    if (event->mimeData()->hasUrls()) {
        QList<QUrl> urls = event->mimeData()->urls();
        if (urls.isEmpty()) {
            return;
        }
        url = urls.front().toLocalFile();
        UpdateTitle();
        Play(url);
    }
}

void HelloPlayerQt::UpdateState() {
    switch (state) {
    case HelloPlayerQt::State::BEGIN:
        ui.startButton->setText("Play");
        break;
    case HelloPlayerQt::State::PLAYING:
        ui.startButton->setText("Pause");
        break;
    case HelloPlayerQt::State::PAUSED:
        ui.startButton->setText("Play");
        break;
    default:
        break;
    }
}

void HelloPlayerQt::UpdateTitle() { setWindowTitle(url); }

void HelloPlayerQt::ReadImageFrame(const unsigned char *buffer, int width,
                                   int height) {
    QImage image(buffer,                   // 图像数据的指针
                 width,                    // image的宽度
                 height,                   // image的高度
                 QImage::Format_RGBA8888); // 图像的像素格式

    //ui.imgWidget->ShowImage(image);
}

void HelloPlayerQt::DebugMsg(const char *msg) {
    //ui.debugMessage->setText(msg);
}

void HelloPlayerQt::Play(const QString &url) {
    AVPlayerProxy::Play(url.toStdString());
}
